<template>
  <doc-alert title="会员用户、标签、分组" url="https://doc.iocoder.cn/member/user/" />

  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="68px"
    >
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          class="!w-240px"
          clearable
          placeholder="请输入用户"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          class="!w-240px"
          clearable
          placeholder="请输入手机号"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="注册时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
          end-placeholder="结束日期"
          start-placeholder="开始日期"
          type="daterange"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="最后登录" prop="loginDate">
        <el-date-picker
          v-model="queryParams.loginDate"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
          end-placeholder="结束日期"
          start-placeholder="开始日期"
          type="daterange"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :show-overflow-tooltip="true"
      :stripe="true"
      class="tableData"
      @selection-change="handleSelectionChange"
    >

      <el-table-column align="center" label="编号" prop="id" width="80px" />
      <el-table-column align="center" label="昵称" prop="nickname" width="180px" />
      <el-table-column align="center" label="手机号" prop="mobile"  />
      <el-table-column align="center" label="用户名称" prop="name"  />
      <el-table-column align="center" label="身份证" prop="idCard"  />
      <el-table-column align="center" label="状态" prop="status" width="100px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        :formatter="dateFormatter"
        align="center"
        label="最后登录"
        prop="loginDate"
      />
      <el-table-column
        :formatter="dateFormatter"
        align="center"
        label="注册时间"
        prop="createTime"
      />
      <el-table-column
        :show-overflow-tooltip="false"
        align="center"
        fixed="right"
        label="操作"
        width="200px"
      >
        <template #default="scope">
          <div class="flex items-center justify-center">
            <el-button link type="primary" @click="openEdit(scope.row.id)">编辑</el-button>
            <el-button link type="primary" @click="openBookHistory(scope.row)">漂书历史</el-button>

          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <UserForm ref="formRef" @success="getList" />
  <!-- 编辑用户弹窗 -->
  <UserEditForm ref="editFormRef" @success="getList" />
  <!-- 修改用户等级弹窗 -->
  <UserLevelUpdateForm ref="updateLevelFormRef" @success="getList" />
  <!-- 修改用户积分弹窗 -->
  <UserPointUpdateForm ref="updatePointFormRef" @success="getList" />
  <!-- 修改用户余额弹窗 -->
  <UserBalanceUpdateForm ref="UpdateBalanceFormRef" @success="getList" />
  <!-- 发送优惠券弹窗 -->
  <CouponSendForm ref="couponSendFormRef" />

  <!-- 漂书历史弹窗 -->
  <Dialog title="漂书历史" v-model="bookHistoryShow" width="1200px">
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <!-- 漂入历史 -->
      <el-tab-pane label="漂入历史" name="in">
        <el-table v-loading="inHistoryLoading" :data="inHistoryList" class="tableData" :stripe="true" :show-overflow-tooltip="true">
          <el-table-column label="编号" align="center" prop="id" width="80px"/>
          <el-table-column label="流程状态" align="center" prop="processStatus" width="100px">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.BK_BOOK_APPLY_STATUS" :value="scope.row.processStatus"/>
            </template>
          </el-table-column>
          <el-table-column label="书籍清单" align="center" width="280px">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="openBooks(scope.row)"
              >
                {{ scope.row.books && scope.row.books.length > 0 ? (scope.row.books.length === 1 ? `《${scope.row.books[0].title}》` : `《${scope.row.books[0].title}》等`) : '查看' }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="数量" align="center" width="70px">
            <template #default="scope">
            {{ scope.row.books.length }}本
            </template>
          </el-table-column>
          <el-table-column label="审核人" align="center" prop="initialReviewName"/>
          <el-table-column label="审核说明" align="center" prop="initialReviewDes"/>
<!--          <el-table-column label="终审人" align="center" prop="finalReviewName"/>-->
<!--          <el-table-column label="终审说明" align="center" prop="finalReviewDes"/>-->
          <el-table-column label="备注" align="center" prop="remark"/>
          <el-table-column
            label="申请时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            width="160px"
          />
        </el-table>
        <!-- 分页 -->
        <Pagination
          v-model:limit="inHistoryParams.pageSize"
          v-model:page="inHistoryParams.pageNo"
          :total="inHistoryTotal"
          @pagination="getInHistoryList"
        />
      </el-tab-pane>

      <!-- 漂出历史 -->
      <el-tab-pane label="漂出历史" name="out">
        <el-table v-loading="outHistoryLoading" :data="outHistoryList"  class="tableData" :stripe="true" :show-overflow-tooltip="true">
          <el-table-column label="编号" align="center" prop="id" width="80px"/>
          <el-table-column label="流程状态" align="center" prop="processStatus" width="100px">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.BK_BOOK_APPLY_STATUS" :value="scope.row.processStatus"/>
            </template>
          </el-table-column>
          <el-table-column label="书籍清单" align="center" width="240px">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="openBooks(scope.row)"
              >
                {{ scope.row.books && scope.row.books.length > 0 ? (scope.row.books.length === 1 ? `《${scope.row.books[0].title}》` : `《${scope.row.books[0].title}》等`) : '查看' }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="审核人" align="center" prop="initialReviewName"/>
          <el-table-column label="审核说明" align="center" prop="initialReviewDes"/>
          <el-table-column label="备注" align="center" prop="remark"/>
          <el-table-column
            label="申请时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            width="160px"
          />
        </el-table>
        <!-- 分页 -->
        <Pagination
          v-model:limit="outHistoryParams.pageSize"
          v-model:page="outHistoryParams.pageNo"
          :total="outHistoryTotal"
          @pagination="getOutHistoryList"
        />
      </el-tab-pane>
    </el-tabs>
  </Dialog>

  <!-- 书籍列表弹窗 -->
  <Dialog title="书籍列表" v-model="booksShow" width="1000px">
    <el-table v-loading="bookLoading" :data="bookList" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="序号" align="center" width="60">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="书名" align="left" prop="title">
        <template #default="scope">
          《{{ scope.row.title }}》
        </template>
      </el-table-column>
      <el-table-column label="出版社" align="left" prop="publisher"/>
      <el-table-column label="isbn" align="left" prop="isbn" width="150"/>
      <el-table-column label="页数" align="left" prop="pageCount" width="60"/>
      <el-table-column
        label="出版时间"
        align="left"
        prop="pubDate"
        :formatter="dateFormatter2"
        width="140px"
      />
    </el-table>
  </Dialog>
</template>
<script lang="ts" setup>
import { dateFormatter, dateFormatter2 } from '@/utils/formatTime'
import * as UserApi from '@/api/member/user'
import { DICT_TYPE } from '@/utils/dict'
import UserForm from './UserForm.vue'
import UserEditForm from './UserEditForm.vue'
import UserLevelUpdateForm from './components/UserLevelUpdateForm.vue'
import UserPointUpdateForm from './components/UserPointUpdateForm.vue'
import UserBalanceUpdateForm from './components/UserBalanceUpdateForm.vue'
import { CouponSendForm } from '@/views/mall/promotion/coupon/components'
import { checkPermi } from '@/utils/permission'
import { LwBookInApplyApi, LwBookInApplyVO } from '@/api/bk/lwbookinapply'
import { LwBookOutApplyApi, LwBookOutApplyVO } from '@/api/bk/lwbookoutapply'
import { LwBookVO } from '@/api/bk/lwbook'

defineOptions({ name: 'MemberUser' })

const message = useMessage() // 消息弹窗

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: null,
  mobile: null,
  loginDate: [],
  createTime: [],
  tagIds: [],
  levelId: null,
  groupId: null
})
const queryFormRef = ref() // 搜索的表单
const editFormRef = ref() // 编辑用户表单
const updateLevelFormRef = ref() // 修改会员等级表单
const updatePointFormRef = ref() // 修改会员积分表单
const UpdateBalanceFormRef = ref() // 修改用户余额表单
const selectedIds = ref<number[]>([]) // 表格的选中 ID 数组

// 漂书历史相关
const bookHistoryShow = ref(false) // 漂书历史弹窗显示状态
const activeTab = ref('in') // 当前激活的tab
const currentUser = ref<UserApi.UserVO>() // 当前查看历史的用户

// 漂入历史
const inHistoryLoading = ref(false) // 漂入历史加载状态
const inHistoryList = ref<LwBookInApplyVO[]>([]) // 漂入历史列表
const inHistoryTotal = ref(0) // 漂入历史总数
const inHistoryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  applyUid: undefined,
  processList: [-1, 100]
})

// 漂出历史
const outHistoryLoading = ref(false) // 漂出历史加载状态
const outHistoryList = ref<LwBookOutApplyVO[]>([]) // 漂出历史列表
const outHistoryTotal = ref(0) // 漂出历史总数
const outHistoryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  applyUid: undefined,
  processList: [-1, 100]
})

// 书籍列表
const booksShow = ref(false) // 书籍列表弹窗显示状态
const bookLoading = ref(false) // 书籍列表加载状态
const bookList = ref<LwBookVO[]>([]) // 书籍列表

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await UserApi.getUserPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 打开会员详情 */
const { push } = useRouter()
const openDetail = (id: number) => {
  push({ name: 'MemberUserDetail', params: { id } })
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 编辑用户操作 */
const openEdit = (id: number) => {
  editFormRef.value.open(id)
}

/** 表格选中事件 */
const handleSelectionChange = (rows: UserApi.UserVO[]) => {
  selectedIds.value = rows.map((row) => row.id)
}

/** 发送优惠券 */
const couponSendFormRef = ref()
const openCoupon = () => {
  if (selectedIds.value.length === 0) {
    message.warning('请选择要发送优惠券的用户')
    return
  }
  couponSendFormRef.value.open(selectedIds.value)
}

/** 操作分发 */
const handleCommand = (command: string, row: UserApi.UserVO) => {
  switch (command) {
    case 'handleUpdate':
      openForm('update', row.id)
      break
    case 'handleUpdateLevel':
      updateLevelFormRef.value.open(row.id)
      break
    case 'handleUpdatePoint':
      updatePointFormRef.value.open(row.id)
      break
    case 'handleUpdateBlance':
      UpdateBalanceFormRef.value.open(row.id)
      break
    default:
      break
  }
}

/** 打开漂书历史 */
const openBookHistory = (user: UserApi.UserVO) => {
  currentUser.value = user
  activeTab.value = 'in'
  bookHistoryShow.value = true
  // 重置分页参数
  inHistoryParams.pageNo = 1
  outHistoryParams.pageNo = 1
  //@ts-ignore
  inHistoryParams.applyUid = user.id
  //@ts-ignore
  outHistoryParams.applyUid = user.id
  // 加载漂入历史
  getInHistoryList()
}

/** 获取漂入历史列表 */
const getInHistoryList = async () => {
  inHistoryLoading.value = true
  try {
    const data = await LwBookInApplyApi.getLwBookInApplyPage(inHistoryParams)
    inHistoryList.value = data.list
    inHistoryTotal.value = data.total
  } finally {
    inHistoryLoading.value = false
  }
}

/** 获取漂出历史列表 */
const getOutHistoryList = async () => {
  outHistoryLoading.value = true
  try {
    const data = await LwBookOutApplyApi.getLwBookOutApplyPage(outHistoryParams)
    outHistoryList.value = data.list
    outHistoryTotal.value = data.total
  } finally {
    outHistoryLoading.value = false
  }
}

/** Tab切换处理 */
const handleTabClick = (tab: any) => {

  if (tab.index === '1') {
    getOutHistoryList()
  } else if (tab.index  === '0') {
    getInHistoryList()
  }
}

/** 打开书籍列表 */
const openBooks = (row: any) => {
  bookList.value = row.books || []
  booksShow.value = true
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
